package com.yao.longhan.ui.fragment;

import com.yao.longhan.ui.base.BaseFragment;

/**
 * Created by heyao on 8/6/17.
 */

public abstract class LazyLoadFragment extends BaseFragment {

    //视图是否已经被初始化
    protected boolean isInit = false;
    //视图是否已经被加载过了
    protected boolean isLoaded = false;

    private void isCanLoad() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            lazyLoad();
            isLoaded = true;
        } else {
            if (isLoaded) {
                isLoaded = false;
                stopLoad();
            }
        }
    }

    /**
     * 当该视图对用户不可见并且已经加载过数据的时候，如果需要在切换到其他页面时停止加载数据，通过覆写此方法实现
     */
    protected abstract void stopLoad();

    /**
     * 当视图初始化并且对可见时加载数据
     */
    protected abstract void lazyLoad();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoad();
    }

    @Override
    protected void initAfter() {
        isInit = true;
        isCanLoad();
    }
}
